//
//  HCGrowthAlbumTableViewCell.m
//  HappyChildren
//
//  Created by WillyZhao on 2017/1/19.
//  Copyright © 2017年 WillyZhao. All rights reserved.
//

#import "HCGrowthAlbumTableViewCell.h"

#import "ZFActionSheet.h"
#import "selectMainVC.h"
#import "CovertPhotoMethod.h"

#import "HCGrowAlumbModel.h"

#import "ImagesJoinTogetherModel.h"

@interface HCGrowthAlbumTableViewCell () <ZFActionSheetDelegate> {
    HCGrowAlumbData *model_;
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *headIMGleftcONTAIN;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *headIMGWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *headIMGHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *labelHeight;

@end

@implementation HCGrowthAlbumTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.headIMGleftcONTAIN.constant = YBKAdaptiveW(83);
    self.headIMGWidth.constant = YBKAdaptiveW(75);
    self.headIMGHeight.constant = YBKAdaptiveW(75);
    self.labelHeight.constant = self.headIMGHeight.constant/2.0;
    self.headIMG.userInteractionEnabled = YES;
    self.headIMG.backgroundColor = [UIColor whiteColor];
    
    self.timeLabel.text = @"072月";
    self.timeLabel.font = YBKSystemFont(YBKAdaptiveFont(30));
    [self.timeLabel setFont:YBKSystemFont(YBKAdaptiveFont(15)) withRange:NSMakeRange(3, 1)];
    [self.timeLabel setFont:YBKSystemFont(YBKAdaptiveFont(14)) withRange:NSMakeRange(2, 1)];
}

-(void)cellWithModel:(NSArray *)array indexPath:(NSIndexPath *)indexpath {
    if (indexpath.row == 0) {
        self.timeLabel.text = @"今天";
        self.timeLabel.font = [UIFont boldSystemFontOfSize:YBKAdaptiveFont(30)];
        self.headIMG.image = [UIImage imageNamed:@"happy_growthalbum_pai"];
        self.contentLabel.text = nil;
        //添加手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureOne:)];
        [self.headIMG addGestureRecognizer:tap];
    }else{
        //添加手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureTwo:)];
        [self.headIMG addGestureRecognizer:tap];
    }
}

-(void)tapGestureOne:(UITapGestureRecognizer *)tap {
//    ZFActionSheet *actionSheet = [ZFActionSheet actionSheetWithTitle:nil confirms:@[@"拍照",@"本地上传"] cancel:@"取消" style:ZFActionSheetStyleCancel];
//    actionSheet.delegate = self;
//    [actionSheet showInView:self.window];
    
    if ([self.delegate respondsToSelector:@selector(pushController)]&&self.delegate) {
        [self.delegate pushController];
    }
}

-(void)tapGestureTwo:(UITapGestureRecognizer *)tap {
    
    if (self.clickHeadimageBlock) {
        
        self.clickHeadimageBlock(model_.pic, model_.time_record, model_.text_record);
    }
}

#pragma mark - 相机调用相关
-(void)clickAction:(ZFActionSheet *)actionSheet atIndex:(NSUInteger)index {
    NSLog(@"点击的位置:%ld",index);

    [self.delegate pushController];
}

-(void)setModel:(id)model loadingView:(HCPopLoadingView *)loading andCount:(NSInteger)count{
    model_ = (HCGrowAlumbData *)model;
    
    if (![PublicFunction isNull:model_.text_record]) {
        self.contentLabel.text = [NSString stringWithFormat:@"%@",model_.text_record];
    }else{
        self.contentLabel.text = @"";
    }
//    NSLog(@"每个单元格的图片数量:%ld",model_.pic.count);
    
    
    
    if (self.cellIndexpath.row !=0) {
        if (self.imageDowd) {
            self.headIMG.image = self.cellImage;
        }else{
            NSMutableArray *arr_images = [NSMutableArray array];
            SDWebImageManager *manager = [SDWebImageManager sharedManager];
            
            [NSThread detachNewThreadWithBlock:^{
                for (int i = 0; i<model_.pic.count; i++) {
                    NSString *key = [manager cacheKeyForURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",model_.pic[i]]]];
                    SDImageCache *cache = [SDImageCache sharedImageCache];
                    UIImage *image_cache = [cache imageFromDiskCacheForKey:key];
                    if (image_cache) {
                        [arr_images addObject:image_cache];
                    }else{
                        [manager downloadImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",model_.pic[i]]] options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                            
                        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                            [arr_images addObject:image];
                        }];
                    }
                    if (arr_images.count == model_.pic.count) {
                        self.headIMG.image = [ImagesJoinTogetherModel imageWithArray:arr_images];
                        self.cellImage = self.headIMG.image;
                        self.imageDowd = YES;
                    }
                }
            }];
            
        }
    }else{
    }
    
    NSString *time = [NSString stringWithFormat:@"%@",model_.time_record];
    NSString *mouth = [time substringWithRange:NSMakeRange(5, 2)];
    NSString *day = [time substringWithRange:NSMakeRange(8, 2)];
    
    self.timeLabel.text = [NSString stringWithFormat:@"%@%@月",day,[self checkTime:mouth]];
    if ([[self checkTime:mouth] integerValue] >=10) {
        self.timeLabel.font = YBKSystemFont(YBKAdaptiveFont(30));
        [self.timeLabel setFont:YBKSystemFont(YBKAdaptiveFont(15)) withRange:NSMakeRange(4, 1)];
        [self.timeLabel setFont:YBKSystemFont(YBKAdaptiveFont(14)) withRange:NSMakeRange(2, 2)];
    }else{
        self.timeLabel.font = YBKSystemFont(YBKAdaptiveFont(30));
        [self.timeLabel setFont:YBKSystemFont(YBKAdaptiveFont(15)) withRange:NSMakeRange(3, 1)];
        [self.timeLabel setFont:YBKSystemFont(YBKAdaptiveFont(14)) withRange:NSMakeRange(2, 1)];
    }
    
    if (self.cellIndexpath.row == (count - 2)) {
        [loading hidden];
    }

}

-(void)setModel:(id)model {
    
    model_ = (HCGrowAlumbData *)model;
    
    if (![PublicFunction isNull:model_.text_record]) {
        self.contentLabel.text = [NSString stringWithFormat:@"%@",model_.text_record];
    }else{
        self.contentLabel.text = @"";
    }
    if (self.cellIndexpath.row !=0) {
        
        if (self.imageDowd) {
            
            self.headIMG.image = self.cellImage;
        }else{
            if (IOS10) {
                NSMutableArray *arr_images = [NSMutableArray array];
//                SDWebImageManager *manager = [SDWebImageManager sharedManager];
                
                [NSThread detachNewThreadWithBlock:^{
                    for (int i = 0; i<model_.pic.count; i++) {
                        NSURL *key =[NSURL URLWithString:[NSString stringWithFormat:@"%@",model_.pic[i]]];
                        //先进行缓存判断
                        if ([[SDWebImageManager sharedManager] cachedImageExistsForURL:key]) {
                            //有缓存的状况下
                            UIImage *im =[[SDImageCache sharedImageCache] imageFromDiskCacheForKey:[NSString stringWithFormat:@"%@",model_.pic[i]]];
                            [arr_images addObject:im];
                        }else{
                            //无缓存状况下
                            [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:key options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                                //进度
                            } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
                                //下载完成
                                [arr_images addObject:image];
                            }];
                        }
                        
                        if (arr_images.count == model_.pic.count) {
                            self.headIMG.image = [ImagesJoinTogetherModel imageWithArray:arr_images];
                            self.cellImage = self.headIMG.image;
                            self.imageDowd = YES;
                        }
                    }
                }];

            }else{
                [NSThread detachNewThreadSelector:@selector(mainThead111) toTarget:self withObject:nil];
            }
        }
    }else{
        
        //第一个cell
        self.timeLabel.text = @"今天";
        self.timeLabel.font = [UIFont boldSystemFontOfSize:YBKAdaptiveFont(30)];
        self.headIMG.image = [UIImage imageNamed:@"happy_growthalbum_pai"];
        self.contentLabel.text = nil;
    }
    
    NSString *time = [NSString stringWithFormat:@"%@",model_.time_record];
    NSString *mouth = [time substringWithRange:NSMakeRange(5, 2)];
    NSString *day = [time substringWithRange:NSMakeRange(8, 2)];
    
    self.timeLabel.text = [NSString stringWithFormat:@"%@%@月",day,[self checkTime:mouth]];
    if ([[self checkTime:mouth] integerValue] >=10) {
        self.timeLabel.font = YBKSystemFont(YBKAdaptiveFont(30));
        [self.timeLabel setFont:YBKSystemFont(YBKAdaptiveFont(15)) withRange:NSMakeRange(4, 1)];
        [self.timeLabel setFont:YBKSystemFont(YBKAdaptiveFont(14)) withRange:NSMakeRange(2, 2)];
    }else{
        self.timeLabel.font = YBKSystemFont(YBKAdaptiveFont(30));
        [self.timeLabel setFont:YBKSystemFont(YBKAdaptiveFont(15)) withRange:NSMakeRange(3, 1)];
        [self.timeLabel setFont:YBKSystemFont(YBKAdaptiveFont(14)) withRange:NSMakeRange(2, 1)];
    }
}

-(NSString *)checkTime:(NSString *)time {
    NSString *fir = [time substringWithRange:NSMakeRange(0, 1)];
    NSString *sec = [time substringWithRange:NSMakeRange(1, 1)];
    if ([fir integerValue] == 0) {

        return sec;
    }else{
        return time;
    }
}

-(void)mainThead111{
    NSMutableArray *arr_images = [NSMutableArray array];
//    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    
//    [NSThread detachNewThreadWithBlock:^{
        for (int i = 0; i<model_.pic.count; i++) {
            
            NSURL *key =[NSURL URLWithString:[NSString stringWithFormat:@"%@",model_.pic[i]]];
            //先进行缓存判断
            if ([[SDWebImageManager sharedManager] cachedImageExistsForURL:key]) {
                //有缓存的状况下
                UIImage *im =[[SDImageCache sharedImageCache] imageFromDiskCacheForKey:[NSString stringWithFormat:@"%@",model_.pic[i]]];
                [arr_images addObject:im];
            }else{
                //无缓存状况下
                [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:key options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                    //进度
                } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
                    //下载完成
                    [arr_images addObject:image];
                }];
            }
            
        
            if (arr_images.count == model_.pic.count) {
                self.headIMG.image = [ImagesJoinTogetherModel imageWithArray:arr_images];
                self.cellImage = self.headIMG.image;
                self.imageDowd = YES;
            }
        }
}

-(void)actionSheetWillDismiss:(BOOL)isShow {
    
}

#pragma mark 左右拼图算法
//leftImage:左侧图片 rightImage:右侧图片 margin:两者间隔
- (UIImage *)combineWithLeftImg:(UIImage*)leftImage rightImg:(UIImage*)rightImage withMargin:(NSInteger)margin{
    
    if (rightImage == nil) {
        return leftImage;
    }
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGFloat width = leftImage.size.width + rightImage.size.width + margin;
    CGFloat height = leftImage.size.height;
    CGSize offScreenSize = CGSizeMake(width, height);
    CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
    // UIGraphicsBeginImageContext(offScreenSize);用这个重绘图片会模糊
    UIGraphicsBeginImageContextWithOptions(offScreenSize, NO, [UIScreen mainScreen].scale);
    CGRect rectL = CGRectMake(0, 0, leftImage.size.width, height);
//    [leftImage drawInRect:rectL];
    CGContextDrawImage(context, rectL, leftImage.CGImage);
    CGRect rectR = CGRectMake(rectL.origin.x + leftImage.size.width + margin, 0, rightImage.size.width, height);
//    [rightImage drawInRect:rectR];
    CGContextDrawImage(context, rectR, rightImage.CGImage);
    UIImage* imagez = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return imagez;
}

-(void)prepareForReuse {
    [self.headIMG.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
}

@end
